package com.lhj.xxsc.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxsc.common.utils.HttpUtils;
import com.lhj.xxsc.member.dao.MemberLevelDao;
import com.lhj.xxsc.member.entity.MemberLevelEntity;
import com.lhj.xxsc.member.exception.PhoneExsitException;
import com.lhj.xxsc.member.exception.UserNameExistException;
import com.lhj.xxsc.member.to.SocialUserTo;
import com.lhj.xxsc.member.to.UserLoginTo;
import com.lhj.xxsc.member.to.UserRegistTo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxsc.common.utils.PageUtils;
import com.xxsc.common.utils.Query;

import com.lhj.xxsc.member.dao.MemberDao;
import com.lhj.xxsc.member.entity.MemberEntity;
import com.lhj.xxsc.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

	@Autowired
	MemberLevelDao memberLevelDao;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<MemberEntity> page = this.page(
				new Query<MemberEntity>().getPage(params),
				new QueryWrapper<MemberEntity>()
		);

		return new PageUtils(page);
	}

	@Override
	public void regist(UserRegistTo to) {
		MemberEntity memberEntity = new MemberEntity();

		// 设置默认登记
		MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
		memberEntity.setLevelId(memberLevelEntity.getId());

		// 检查手机名和手机号是否唯一
		checkPhone(to.getPhone());
		checkUserName(to.getUserName());

		memberEntity.setMobile(to.getPhone());
		memberEntity.setUsername(to.getUserName());
		// 密码使用spirng整合的 加盐 md5 加密
		/**
		 *
		 */
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		memberEntity.setPassword(encoder.encode(to.getPassword()));
		memberEntity.setNickname(to.getUserName());
		/**
		 * 其他默认信息
		 */

		// 保存
		MemberDao memberDao = this.getBaseMapper();
		memberDao.insert(memberEntity);
	}

	@Override
	public void checkPhone(String phone) throws PhoneExsitException {
		Integer mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
		if (mobile > 0) {
			throw new PhoneExsitException();
		}

	}

	@Override
	public void checkUserName(String userName) throws UserNameExistException {
		Integer username = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
		if (username > 0) {
			throw new UserNameExistException();
		}
	}

	@Override
	public MemberEntity login(SocialUserTo to) throws Exception {
		// 登录和注册合并
		String uid = to.getUid();
		// 判断当前用户是否已经登录过
		MemberDao memberDao = this.baseMapper;
		MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
		if (memberEntity != null) {
			//已经注册过 更新令牌
			memberEntity.setAccessToken(to.getAccess_token());
			memberEntity.setExpiresIn(to.getExpires_in());
			memberDao.updateById(memberEntity);
			return memberEntity;
		} else {
			// 注册社交信息
			MemberEntity memberEntityNew = new MemberEntity();

			try {
				// 查询出当前社交用户的个人信息
				Map<String, String> query = new HashMap<>();
				query.put("access_token", to.getAccess_token());
				query.put("uid", to.getUid());
				HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
				if (response.getStatusLine().getStatusCode() == 200) {
					String userJson = EntityUtils.toString(response.getEntity());
					JSONObject jsonObject = JSON.parseObject(userJson);
					String name = jsonObject.getString("name");
					String gender = jsonObject.getString("gender");
					memberEntityNew.setUsername(name);
					memberEntityNew.setNickname(name);
					memberEntityNew.setGender("m".equals(gender) ? 1 : 0);
				}
			} catch (Exception e) {

			}
			memberEntityNew.setSocialUid(uid);
			memberEntityNew.setAccessToken(to.getAccess_token());
			memberEntityNew.setExpiresIn(to.getExpires_in());
			memberDao.insert(memberEntityNew);
			return memberEntityNew;
		}
	}

	@Override
	public MemberEntity login(UserLoginTo to) {
		String loginacct = to.getLoginacct();
		String password = to.getPassword();

		// 去数据库查询
		MemberDao memberDao = this.getBaseMapper();
		MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
		if (memberEntity == null) {
			// 登录失败
			return null;
		} else {
			// 数据库中存的密码
			String passwordDb = memberEntity.getPassword();
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			// 校验结果
			boolean matches = encoder.matches(password, passwordDb);
			if (matches) {
				return memberEntity;
			} else {
				return null;
			}
		}

	}

}
